import "dart:convert";
import "dart:math";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/associated_devices/sections/associated_block.dart";
import "package:ct_pa_majordomo/pages/apartment/associated_devices/widgets/associate_unbind_devices/index.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class AssociatedDevices extends StatefulWidget {
  final int roomId;
  final String roomName;
  final String buildingName;
  const AssociatedDevices({super.key, required this.roomId, required this.roomName, required this.buildingName});

  @override
  State<StatefulWidget> createState() => _AssociatedDevicesState();
  
}

class _AssociatedDevicesState extends State<AssociatedDevices> with TickerProviderStateMixin{

  List _list = [];
  Map _associatedDevice = {
    "room_lock": false,
    "room_electricity_meter": false,
    "room_face_lock": false,
  };
  Map _typeDict = {
    1: "房间锁",
    2: "房间电表",
    3: "门禁",
  };

  void _getDeviceList() async {
    EasyLoading.show();
    Map resData = await apartmentApi.deviceList(widget.roomId);
    EasyLoading.dismiss();
    print("关联设备：>>>$resData");
    setState(() {
      _list = resData["data"] ?? [];
    });
  }

  void _unbindDevice(Map item) async {
    int id;
    EasyLoading.show();
    switch (item["deviceType"]) {
      case 1:///门锁
        id = item["lockId"];
        await lockApi.unbindRoom(id);
        _associatedDevice["room_lock"] = false;
        break;
      case 2:///电表
        id = item["electricityMeterId"];
        await electricityMeterApi.unbindRoom(id);
        _associatedDevice["room_electricity_meter"] = false;
        break;
      case 3:///门禁
        id = item["faceLockId"];
        await entranceGuardApi.unbindRoom(id, widget.roomId);
        _associatedDevice["room_face_lock"] = false;
        break;
    }
    EasyLoading.dismiss();
    _getDeviceList();

  }

  Widget _deviceItem(Map item,) {
    String name = "";
    Widget tip = SizedBox();
    IconData deviceIcon;
    switch (item["deviceType"]) {
      case 1:///门锁
        name = item["lockName"];
        _associatedDevice["room_lock"] = true;
        deviceIcon = Icons.lock_outlined;
        tip = Row(
          children: [
          const Icon(Icons.battery_5_bar_outlined, color: ThemeVars.colorWarning),
          Text("${item["electricQuantity"] ?? 0}%", style: const TextStyle(fontSize: 12, color: ThemeVars.colorWarning),)
          ],
        );
      case 2:///电表
        name = item["name"];
        _associatedDevice["room_electricity_meter"] = true;
        deviceIcon = Icons.electric_meter_outlined;
        tip = Text("电表号：${item["number"]}", style: const TextStyle(fontSize: 12, color: ThemeVars.colorWarning),);
      case 3:///电表
        name = item["faceLockName"];
        _associatedDevice["room_face_lock"] = true;
        deviceIcon = Icons.lock_outlined;
        tip = Text("状态：${item["statusName"]}", style: const TextStyle(fontSize: 12, color: ThemeVars.colorWarning),);
      default:
        deviceIcon = Icons.device_unknown;
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(name, textAlign: TextAlign.left,),
        const SizedBox(height: 12,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            tip,
            GestureDetector(
              onTap: () {
                taiDialog(
                    context: context,
                    child: Text("解除关联${_typeDict[item["deviceType"]]}？", textAlign: TextAlign.center,),
                    onConfirm: (taiContext) {
                      Navigator.of(taiContext).pop();
                      _unbindDevice(item);
                    }
                );
              },
              child: const Icon(Icons.remove_circle_outline, color: ThemeVars.colorError,),
            ),
          ],
        )
      ],
    );
  }

  Widget _tag(Map item) {

    return Positioned(
        right: 0,
        top: 0,
        child: Container(
          width: 60,
          height: 20,
          alignment: Alignment.center,
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomLeft: Radius.circular(15)),
            color: ThemeVars.colorPrimaryLight,
          ),
          child: Text(_typeDict[item["deviceType"]] ?? "--", style: TextStyle(fontSize: 10),),
        )
    );
  }

  List<Widget> _renderList() {
    if (_list.isEmpty) {
      return [
        const Padding(
          padding: EdgeInsets.only(top: 60),
          child: Column(
            children: [
              Icon(Icons.hourglass_empty_outlined, size: 60, color: ThemeVars.colorPrimaryLight,),
              Text("暂无关联设备"),
            ],
          ),
        )
      ];
    }
    return List.generate(_list.length * 2 - 1, (index) {
      if (index.isOdd) {
        return const SizedBox(height: 12,);
      }
      Map item = _list[index ~/ 2];
      IconData deviceIcon = item["deviceType"] == 1 ? 
          Icons.lock_outlined : 
          Icons.electric_meter_outlined;
          
      return DecoratedBox(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white,
        ),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              child: Row(
                children: [
                  Icon(deviceIcon, size: 40,),
                  SizedBox(width: 12,),
                  Expanded(
                      child: _deviceItem(item),
                  )
                ],
              ),
            ),
            _tag(item),
          ],
        ),
      );
    });
  }

  void _showBottomSheet({
    required String title,
    required AssociatedType type,
  }) async {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                padding: const EdgeInsets.fromLTRB(20, 12, 20, 20),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                  color: Colors.white
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(title),
                    const SizedBox(height: 12,),
                    Wrap(
                      direction: Axis.horizontal,
                      alignment: WrapAlignment.start,
                      spacing: 20,
                      runSpacing: 12,
                      children: [
                        SizedBox(
                          width: (MediaQuery.of(context).size.width - ThemeVars.paddingPage * 2 - 40 - 20) / 2,
                          child: AssociatedBlock(
                            title: "智能锁",
                            icon: const Icon(Icons.lock_open_outlined),
                            disabled: _associatedDevice["room_lock"],
                            onTap: () {
                              Navigator.pop(context);
                              Stacker.pushNamed(
                                Keys.APARTMENT_ASSOCIATED_DEVICES_LOCK,
                                arguments: { "type": type, "roomId": widget.roomId, "roomName": widget.roomName, "buildingName": widget.buildingName, "deviceType": DeviceType.lock },
                              ).then((refresh) {
                                  if (refresh != null && refresh as bool) {
                                    _getDeviceList();
                                  }
                              });
                            },
                          )
                        ),
                        // const SizedBox(width: 20,),
                        SizedBox(
                          width: (MediaQuery.of(context).size.width - ThemeVars.paddingPage * 2 - 40 - 20) / 2,
                          child: AssociatedBlock(
                            title: "电表",
                            icon: const Icon(Icons.lock_open_outlined),
                            disabled: _associatedDevice["room_electricity_meter"],
                            onTap: () {
                              Navigator.pop(context);
                              Stacker.pushNamed(
                                Keys.APARTMENT_ASSOCIATED_DEVICES_LOCK,
                                arguments: { "type": type, "roomId": widget.roomId, "roomName": widget.roomName, "buildingName": widget.buildingName,"deviceType": DeviceType.electricityMeter },
                              ).then((refresh) {
                                if (refresh != null && refresh as bool) {
                                  _getDeviceList();
                                }
                              });
                            },
                          )
                        ),
                        SizedBox(
                            width: (MediaQuery.of(context).size.width - ThemeVars.paddingPage * 2 - 40 - 20) / 2,
                            child: AssociatedBlock(
                              title: "门禁",
                              icon: const Icon(Icons.lock_open_outlined),
                              disabled: _associatedDevice["room_face_lock"],
                              onTap: () {
                                Navigator.pop(context);
                                Stacker.pushNamed(
                                  Keys.APARTMENT_ASSOCIATED_DEVICES_LOCK,
                                  arguments: { "type": type, "roomId": widget.roomId, "roomName": widget.roomName, "buildingName": widget.buildingName,"deviceType": DeviceType.faceLock },
                                ).then((refresh) {
                                  if (refresh != null && refresh as bool) {
                                    _getDeviceList();
                                  }
                                });
                              },
                            )
                        ),
                      ],
                    )
                  ],
                ),
              ),
              const SizedBox(height: 12,),
              Button(
                type: ButtonType.normal,
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text("取消", style: TextStyle(color: ThemeVars.colorText),)
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void initState() {
    _getDeviceList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "智能设备",
      child: Stack(
        children: [
          ListView(
            padding: EdgeInsets.all(ThemeVars.paddingPage),
            children: [
              Text("已关联："),
              SizedBox(height: 12,),
              ..._renderList(),
            ],
          ),
          Positioned(
            bottom: 0,
            left: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              height: 40,
              decoration: BoxDecoration(
                  color: ThemeVars.colorPrimary
              ),
              child: Row(
                children: [
                  Expanded(child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      _showBottomSheet(title: "关联房间设备", type: AssociatedType.room);
                    },
                    child: const Text("关联房间", style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),
                  ),),
                  Container(
                    height: 20,
                    width: 1,
                    decoration: const BoxDecoration(
                        color: Colors.white
                    ),
                  ),
                  Expanded(child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      _showBottomSheet(title: "关联公区设备", type: AssociatedType.public);
                    },
                    child: const Text("关联公区", style: TextStyle(color: Colors.white), textAlign: TextAlign.center,),
                  ),),
                ],
              ),
            ),
          ),

        ],
      )
    );
  }
  
}